package com.tozed.android.launcher.simpleui;

import android.os.Handler;
import android.os.Message;

public class DoTaskOnceAtFirstOrAtLast {
	private static final String TAG = "DoTaskOnceAtFirstOrAtLast ";
	
	private static final int DO_TIME_COUNT_MESSAGE = 100;
	private static final int DO_ONCE_ATFIRST_MESSAGE = 101;
	private static final int DO_ONCE_ATLAST_MESSAGE = 102;
	private static final int DO_ONCE_DELAY = 500;
	private static long sDelayedTime = 0;
	private static boolean sHasDone = false;
	private static Handler sTargetHandler;
	
	private static Object[] obj = new Object[1];
	
	private static Handler sHandler = new Handler()
    {
      public void handleMessage(Message msg)
      {
          switch (msg.what)
          {
	          case DO_TIME_COUNT_MESSAGE:
	          {
		        	synchronized (obj){
		        	  sHasDone = false;
					}
		      }
	          break;
	          
	          case DO_ONCE_ATFIRST_MESSAGE:
	          case DO_ONCE_ATLAST_MESSAGE:
	          {
	        	  Runnable runnable = (Runnable)msg.obj;
	        	  if (runnable != null)
	        	  {
	        		  if (DoTaskOnceAtFirstOrAtLast.sTargetHandler == null){
		            	  runnable.run();
		              }else{
		            	  sTargetHandler.postDelayed(runnable, sDelayedTime);
		                  sTargetHandler = null;
		              }
	        	  }
	          }
	          break;
	          
          }
      }
    };
	
	
	public static void doTaskOnceAtFirst(Runnable runnable)
	{
		synchronized (obj)
		{
			try{
				if (!sHasDone)
				{
					sHasDone = true;
					
					Message msg = sHandler.obtainMessage();
					msg.obj = runnable;
					msg.what = DO_ONCE_ATFIRST_MESSAGE;
					sHandler.sendMessage(msg);
					
					sHandler.removeMessages(DO_TIME_COUNT_MESSAGE);
					sHandler.sendEmptyMessageDelayed(DO_TIME_COUNT_MESSAGE, DO_ONCE_DELAY);
				}
			} finally {
				
			}
		}
	}
	
	public static void doTaskOnceAtLast(Runnable runnable)
	{
		synchronized (obj)
		{
			try{
				Message msg = sHandler.obtainMessage();
				msg.obj = runnable;
				msg.what = DO_ONCE_ATLAST_MESSAGE;
				
				sHandler.removeMessages(DO_ONCE_ATLAST_MESSAGE);
				
				sHandler.sendMessageDelayed(msg, DO_ONCE_DELAY);
			} finally {
				
			}
		}
	}
	
	public static void setTargetHandler(Handler targetHandler, long delayedTime)
	{
	  sTargetHandler = targetHandler;
	  sDelayedTime = delayedTime;
	}
}
